/**
 * @(#) ModVacationMediator.as
 *
 * @date		2009. 03. 06.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	근무 - Mediator
 * 				근무관리 Presentation Logic을 관리 
 */
package com.skt.common_hr.work_sac.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.approval.RequestApprovalMediator;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.skt.common_hr.work_sac.WorkFacade;
	import com.skt.common_hr.work_sac.model.CalendarProxy;
	import com.skt.common_hr.work_sac.model.ReqVacationProxy;
	import com.skt.common_hr.work_sac.model.VacationApprovalProxy;
	import com.skt.common_hr.work_sac.model.VacationCodeProxy;
	import com.skt.common_hr.work_sac.model.VacationQuotaProxy;
	import com.skt.common_hr.work_sac.model.vo.ReqVacationVO;
	import com.skt.common_hr.work_sac.view.components.ModVacationView;
	import com.wcl.utils.StringUtil;
	
	import flash.events.Event;
	
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	
	public class ModVacationMediator extends CommonMediator
	{
		public static const NAME:String = "ModVacationMediator"; 

		public var baseDate:Date;	
		
		public var _savingTable:Array;
		private var _currentKey:String;
		private var GWAREKEY:String;
		
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function ModVacationMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
            view.callLater(initView);
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		private function initView():void
 		{
			setEventListener();
 			// 휴가사용일수를 가져오고
 			var quotaProxy:VacationQuotaProxy = facade.retrieveProxy(VacationQuotaProxy.NAME) as VacationQuotaProxy;
			view.quotaList = quotaProxy.quotaList;
			// 휴가 코드리스트를 가져온다.
 			var codeProxy:VacationCodeProxy = facade.retrieveProxy(VacationCodeProxy.NAME) as VacationCodeProxy;
			view.vacationCodeList = codeProxy.vacationList;
			
			var calendarProxy:CalendarProxy = facade.retrieveProxy(CalendarProxy.NAME) as CalendarProxy;
			view.bHoliVacation = calendarProxy.bHoliVacation;

 		}
		
		public function exec(date:Date, key:String):void
		{
			bActivated = true;
			baseDate = new Date(date);
			GWAREKEY = key;
			loadData();
		}		
		
		
		private function loadData():void
		{
			var vacProxy:ReqVacationProxy = facade.retrieveProxy(ReqVacationProxy.NAME) as ReqVacationProxy;
			vacProxy.load(GWAREKEY);
		}
		
		private function setEventListener():void
		{
 			// 각 버튼들의 Event Handler를 설정하고
 			view.addEventListener(ModVacationView.CONFIRM, onConfirm);
 			view.addEventListener(ModVacationView.DELETE, onDelete);
 			view.addEventListener(ModVacationView.CANCEL, onCancel);
 			
 			view.addEventListener(ModVacationView.ADD_RECORD, onClickAddRecord);
 			view.addEventListener(ModVacationView.DEL_RECORD, onDelRecord);
		}
		
		private function removeEventListener():void
		{
 			view.removeEventListener(ModVacationView.CONFIRM, onConfirm);
 			view.removeEventListener(ModVacationView.DELETE, onDelete);
 			view.removeEventListener(ModVacationView.CANCEL, onCancel);
 			
 			view.removeEventListener(ModVacationView.ADD_RECORD, onClickAddRecord);
 			view.removeEventListener(ModVacationView.DEL_RECORD, onDelRecord);
		}
		
		
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					WorkFacade.LOAD_REQ_VACATION_COMPLETE,
					WorkFacade.LOAD_REQ_VACATION_FAILED,
					WorkFacade.DELETE_REQ_VACATION_COMPLETE,
					WorkFacade.DELETE_REQ_VACATION_FAILED,
					WorkFacade.INSERT_REQ_VACATION_COMPLETE,
					WorkFacade.INSERT_REQ_VACATION_FAILED,
					RequestApprovalMediator.APPROVAL_CANCEL,
					RequestApprovalMediator.APPROVAL_COMPLETE
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			if(bActivated) {
				switch(note.getName()) 
				{
					case WorkFacade.LOAD_REQ_VACATION_COMPLETE:
						view.reqList = (note.getBody() as ReqVacationProxy).reqVacationList;
						if(view.reqList.length>0) {
							view.cause = view.reqList.getItemAt(0).TEXT2;
						}
						break;
					case WorkFacade.INSERT_REQ_VACATION_COMPLETE:
						_currentKey = ReqVacationProxy(note.getBody()).outKey; 
						execApproval(_currentKey);
						break;
					case WorkFacade.INSERT_REQ_VACATION_FAILED:
					case WorkFacade.DELETE_REQ_VACATION_FAILED:
						CommonAlert.showMessage(commonFacade.bundle, "("+note.getBody().retCode+")"+note.getBody().retText, null, "RFC 오류", view);
						break;
					case WorkFacade.DELETE_REQ_VACATION_COMPLETE:
						closeView();
						break;
					case RequestApprovalMediator.APPROVAL_COMPLETE:					// 결재 요청  성공
						closeView();
						break;
					case RequestApprovalMediator.APPROVAL_CANCEL:					// 결재 요청 취소
						break;
					default:
						//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
						break;
				}
			}
		}
		
		private function closeView(bCancel:Boolean = false):void
		{
 			PopUpManager.removePopUp(view);
 			bActivated = false;
			facade.sendNotification((bCancel) ? WorkFacade.CANCEL_REQ_WORKTIME : WorkFacade.SUCCEED_REQ_WORKTIME, this);
		}
		

 		private function onDelete(event:Event):void
 		{
 			var proxy:ReqVacationProxy = facade.retrieveProxy(ReqVacationProxy.NAME) as ReqVacationProxy;
 			proxy.del([{GWAREKEY: GWAREKEY}]);
 		}
 		
 		private function onCancel(event:Event):void
 		{
 			closeView(true);
 			
 		}
 		
 		private function onClickAddRecord(event:Event):void
 		{
 			addRecord();
 		}
 		
 		
 		private function addRecord():void
 		{
 			var vo:ReqVacationVO = new ReqVacationVO();
 			vo.selectedIndex = 0;
 			vo.BEGDA = new Date(baseDate);
 			vo.ENDDA = new Date(baseDate);
 			view.reqList.addItem(vo);
 		}
 		
 		private function onDelRecord(event:Event):void
 		{
			for (var i:int=0; i<view.reqList.length; i++)
			{
				if(view.reqList.getItemAt(i).del) {
					view.reqList.removeItemAt(i--);
				}
			} 			
			if(view.reqList.length==0) {
	 			var vo:ReqVacationVO = new ReqVacationVO();
	 			vo.BEGDA = new Date(baseDate);
	 			vo.ENDDA = new Date(baseDate);
	 			view.reqList.addItem(vo);
			}
 		}

  		private function onConfirm(event:Event):void
 		{
 			var table:Array = new Array();
 			var i:int = 0;
 			for each(var src:ReqVacationVO in view.reqList)
 			{
 				if(src.selectedIndex<=0) {
 					CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_VACATIONTYPE");
 					return;
 				}
 				if(Number(src.BEGDA) > Number(src.ENDDA)) {
 					CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_VACATIONTIME");
 					return;
 				}
 				if(!checkHoliday(src.BEGDA) && !view.bHoliVacation) {
 					CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_VACATION_DATE");
 					return;
 				}
 				if(StringUtil.NVL(src.TEXT1) == "") {
 					CommonAlert.showMessage(commonFacade.bundle, "휴가 신청 사유를 반드시 입력하여 주십시오.");
 					return;
 				} 
 				src.SEQNO = (i++).toString();
 				src.PERNR = src.IPERNR = Variables.myPernr;
 				src.DGBN  = "1";
 				src.BEGUZ = null;
 				src.ENDUZ = null;
 				src.AWART = view.vacationCodeList.getItemAt(src.selectedIndex).code;
 				src.AWATX = view.vacationCodeList.getItemAt(src.selectedIndex).text;
 				src.GWAREKEY = GWAREKEY;
 				if(src.AWART=="0120") // 반차
 				{
 					src.APM = (src.bAM==true) ? "A" : "P";
 					src.ENDDA = src.BEGDA;
 				}
 				table.push(src);
 			}
 			_savingTable = table;
 			saveVacation(table);
 		}
 		
  		private function saveVacation(table:Array):void
 		{
			var proxy:ReqVacationProxy = facade.retrieveProxy(ReqVacationProxy.NAME) as ReqVacationProxy;
  			_savingTable = table;
			proxy.InsertVacation("2", table);
 		}

 		private function execApproval(key:String):void
 		{
 			var approval:RequestApprovalMediator = facade.retrieveMediator(RequestApprovalMediator.NAME) as RequestApprovalMediator;
 			if(approval==null) {
 				approval = new RequestApprovalMediator(view, "01");
 				facade.registerMediator(approval);
 			}
 			
 			var appProxy:VacationApprovalProxy = facade.retrieveProxy(VacationApprovalProxy.NAME) as VacationApprovalProxy;
 			appProxy.key = key;
 			appProxy.dataProvider = _savingTable;
 			approval.execRequest(view, appProxy);
 		}

		private function checkHoliday(target:Date):Boolean
 		{
 			if(target.day==0 || target.day==6) {
 				return false;
 			}
			return  true;
 		}
 		

 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():ModVacationView
        {
            return viewComponent as ModVacationView;
        }
	}
}